<template>
  <div class="task-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" size="default">
        <el-form-item label="任务名称">
          <el-input v-model="searchForm.task_name" placeholder="请输入任务名称" clearable />
        </el-form-item>
        <el-form-item label="数据源">
          <el-select v-model="searchForm.db_info_setting_id" placeholder="请选择数据源" clearable style="width: 220px;">
            <el-option 
              v-for="item in dataSourceOptions" 
              :key="item._id" 
              :label="item.connection_name" 
              :value="item._id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标表名">
          <el-input v-model="searchForm.table_name" placeholder="请输入目标表名" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option :label="'禁用'" :value="0" />
            <el-option :label="'启用'" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
          <el-button type="primary" :icon="Refresh" circle @click="fetchTaskList" />
        </div>
      </template>
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="task_name" label="任务名称" min-width="150" />
        <el-table-column prop="db_name" label="数据源" min-width="150" />
        <el-table-column prop="table_name" label="目标表名" min-width="150" />
        <el-table-column prop="query_condition" label="数据条件" min-width="180" :show-overflow-tooltip="true" />
        <el-table-column prop="data_limit" label="获取数据量" width="100" align="center">
          <template #default="{ row }">
            {{ row.data_limit || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="cron_expression" label="Cron表达式" width="150" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_by" label="创建人" width="100" />
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ row.updated_at ? formatDateTime(row.updated_at) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="updated_by" label="更新人" width="100">
          <template #default="{ row }">
            {{ row.updated_by || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button 
                type="success" 
                size="small" 
                @click="handleExecute(row)"
                :loading="row.executing"
                :disabled="row.executing"
              >
                {{ row.executing ? '执行中' : '执行' }}
              </el-button>
              <el-button :type="row.status === 1 ? 'warning' : 'success'" size="small" @click="handleToggleStatus(row)">
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-tooltip content="查看该任务的执行日志" placement="top" effect="dark">
                <el-button type="info" size="small" @click="viewTaskLogs(row)">日志</el-button>
              </el-tooltip>
              <el-tooltip content="删除该任务" placement="top" effect="dark">
                <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <task-form
      v-model:visible="formVisible"
      :form-data="formData"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />
    
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus } from '@element-plus/icons-vue';
import { getTaskList, getDataSourceList, executeTask, deleteTask, updateTaskStatus } from '@/api/data-sync';
import TaskForm from './components/TaskForm.vue';
import { useRouter } from 'vue-router';

// 获取路由实例
const router = useRouter();

// 搜索表单
const searchFormRef = ref();
const searchForm = reactive({
  task_name: '',
  db_info_setting_id: '',
  table_name: '',
  status: null
});

// 数据源选项
const dataSourceOptions = ref<any[]>([]);

// 表格数据
const tableData = ref<any[]>([]);
const tableLoading = ref(false);

// 执行中的任务ID记录
const executingTaskIds = ref<Set<string>>(new Set());

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 日期格式化函数
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 表单相关
const formVisible = ref(false);
const formData = ref<any>({});
const isEdit = ref(false);

// 获取数据源列表
const fetchDataSourceList = async () => {
  try {
    const res: any = await getDataSourceList();
    if (res.code === 200 && res.data) {
      dataSourceOptions.value = res.data;
    }
  } catch (error) {
    console.error('获取数据源列表失败:', error);
  }
};

// 获取任务列表
const fetchTaskList = async () => {
  try {
    tableLoading.value = true;
    
    const params = {
      ...searchForm,
      page: pagination.currentPage,
      size: pagination.pageSize
    };
    
    const res: any = await getTaskList(params);
    
    if (res.code === 200) {
      // 处理数据,添加数据源名称和执行状态
      tableData.value = res.data.map((item: any) => {
        // 通过db_info_setting_id找到对应的数据源名称
        const dataSource = dataSourceOptions.value.find(source => source._id === item.db_info_setting_id);
        return {
          ...item,
          db_name: dataSource ? dataSource.connection_name : '未知数据源',
          executing: executingTaskIds.value.has(item._id)
        };
      });
      pagination.total = res.total || res.data.length;
    } else {
      ElMessage.error(res.message || '获取任务列表失败');
    }
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
  } finally {
    tableLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchTaskList();
};

// 重置
const handleReset = () => {
  searchFormRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchTaskList();
};

// 新增
const handleAdd = () => {
  // 使用完全新的对象，而不是修改现有对象
  formData.value = Object.assign({}, {
    task_name: '',
    db_info_setting_id: '',
    table_name: '',
    query_condition: '',
    data_limit: null,
    cron_expression: '0 0 * * * ?', // 默认每天0点执行
    status: 0, // 默认禁用
    details: [],
    ts_mapping: []
  });
  isEdit.value = false;
  // 确保先关闭再打开，强制组件重新渲染
  formVisible.value = false;
  setTimeout(() => {
    formVisible.value = true;
  }, 0);
};

// 编辑
const handleEdit = (row: any) => {
  // 使用深拷贝，确保不会修改原始数据
  formData.value = JSON.parse(JSON.stringify(row));
  isEdit.value = true;
  formVisible.value = true;
};

// 表单提交成功回调
const handleFormSuccess = () => {
  formVisible.value = false;
  fetchTaskList();
};

// 执行任务
const handleExecute = async (row: any) => {
  try {
    ElMessageBox.confirm(`确认立即执行任务"${row.task_name}"?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // 设置执行状态
      executingTaskIds.value.add(row._id);
      // 更新表格中的执行状态
      const index = tableData.value.findIndex(item => item._id === row._id);
      if (index !== -1) {
        tableData.value[index].executing = true;
      }
      
      try {
        const res: any = await executeTask(row._id);
        
        if (res.code === 200) {
          ElMessage.success('任务执行成功');
          // 更新任务的最后执行时间
          if (index !== -1) {
            tableData.value[index].last_execution_time = new Date().toISOString();
          }
        } else {
          ElMessage.error(res.message || '任务执行失败');
        }
      } finally {
        // 无论成功与否，都要移除执行状态
        executingTaskIds.value.delete(row._id);
        // 更新表格中的执行状态
        const updateIndex = tableData.value.findIndex(item => item._id === row._id);
        if (updateIndex !== -1) {
          tableData.value[updateIndex].executing = false;
        }
      }
    }).catch(() => {
      // 用户取消了操作，什么都不做
    });
  } catch (error) {
    console.error('执行任务失败:', error);
    ElMessage.error('执行任务失败');
  }
};

// 切换状态
const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1;
    const statusText = newStatus === 1 ? '启用' : '禁用';
    
    ElMessageBox.confirm(`确认${statusText}任务"${row.task_name}"?`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res: any = await updateTaskStatus(row._id, newStatus);
      if (res.code === 200) {
        ElMessage.success(`${statusText}成功`);
        fetchTaskList();
      } else {
        ElMessage.error(res.message || `${statusText}失败`);
      }
    });
  } catch (error) {
    console.error('更新任务状态失败:', error);
    ElMessage.error('更新任务状态失败');
  }
};

// 删除任务
const handleDelete = async (row: any) => {
  try {
    ElMessageBox.confirm(`确认删除任务"${row.task_name}"?`, '删除提示', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
      distinguishCancelAndClose: true,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = '删除中...';
          
          deleteTask(row._id).then((res: any) => {
            instance.confirmButtonLoading = false;
            if (res.code === 200) {
              ElMessage.success('删除成功');
              fetchTaskList();
            } else {
              ElMessage.error(res.message || '删除失败');
            }
            done();
          }).catch(error => {
            instance.confirmButtonLoading = false;
            ElMessage.error('删除失败');
            console.error('删除任务失败:', error);
            done();
          });
        } else {
          done();
        }
      }
    }).catch(() => {
      // 取消删除操作
      ElMessage.info('已取消删除');
    });
  } catch (error) {
    console.error('删除任务失败:', error);
    ElMessage.error('删除任务失败');
  }
};

// 查看任务日志
const viewTaskLogs = (row: any) => {
  router.push({
    // 使用正确的路由路径格式
    path: '/log',
    query: { 
      taskId: row._id,
      taskName: row.task_name // 传递任务名称以便在日志页显示
    }
  });
  ElMessage.info(`正在查看"${row.task_name}"的执行日志`);
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  fetchTaskList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchTaskList();
};

// 页面初始化
onMounted(async () => {
  await fetchDataSourceList();
  await fetchTaskList();
});
</script>

<style lang="scss" scoped>
.task-container {
  .search-card {
    margin-bottom: 16px;
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
  }

  .execution-status {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .executing-icon {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #fff;
    margin-right: 5px;
    animation: pulse 1s infinite;
  }
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.4;
  }
  100% {
    opacity: 1;
  }
}

:deep(.el-message-box__message) {
  word-break: break-word;
}
</style>